package com.huantai.auth.exception;

import com.alibaba.fastjson.JSON;
import com.huantai.common.dto.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import static com.huantai.auth.enums.ResultEnum.SYS_ERROR;

/**
 * 异常拦截器
 */
@Slf4j
@ControllerAdvice
public class AppExceptionHandler {

    @ResponseBody
    @ExceptionHandler(BizException.class)
    public ResponseEntity<BaseResponse<String>> handleBusiException(BizException e) {
        BaseResponse<String> result = new BaseResponse();
        result.setMessage(e.getMessage());
        result.setCode(e.getErrorCode());
        log.info("请求返回: {}", JSON.toJSONString(result));
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseEntity<BaseResponse<String>> handleCommonException(Exception e) {
        BaseResponse<String> result = new BaseResponse();
        result.setCode(SYS_ERROR.getCode());
        result.setMessage(SYS_ERROR.getMessage());
        log.error("系统出错：", e);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
}
